const http = require('http')
const url = require('url')
const path = require('path')
const fs = require('fs')
const mime = require('mime')
const querystring = require('querystring')
const uuid = require('uuid')

Buffer.prototype.split = function (sep) {
    let len = Buffer.from(sep).length;
    let offset = 0;
    let current;
    let arr = [];

    while (-1 !== (current = this.indexOf(sep, offset))) {
        arr.push(this.slice(offset, current))
        offset = current + len
    }
    arr.push(this.slice(offset))
    return arr;
}

const uploadPath = path.resolve(__dirname, 'upload');

const server = http.createServer((req, res) => {
    if (pathname === '/login' && req.method === 'POST') {
        const buffer = [];
        req.on('data', function (chunk) {
            buffer.push(chunk)
        })
        req.on('end', function () {
            let buf = Buffer.concat(buffer);
            if (req.headers['content-type'] === 'application/json') {
                let obj = JSON.parse(buf.toString());
                res.setHeader('Content-Type', 'application/json')
                res.end(JSON.stringify(obj))
            } else if (req.headers['content-type'] === 'text/plain') {
                res.setHeader('Contet-Type', 'text/plain')
                res.end(buf.toString())
            } else if(req.headers['content-type'] === 'application/x-www-form-urlencoded') {
                let r = querystring.parse(buf.toString(),'&','=')
                res.end(JSON.stringify(r))
            } else if(req.headers['content-type'].includes('multipart/form-data')) {
                let boundary = "--" + req.headers['content-type'].split('=')[1];
                let lines = buf.split(boundary).slice(1,-1)
                const r = {};
                lines.forEach(line = >{
                    
                })
            }
        })
    }
})